package com.basic.modules.nykf.service.impl;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.common.utils.R;
import com.basic.modules.nykf.dao.FileNewDao;
import com.basic.modules.nykf.entity.FileNewEntity;
import com.basic.modules.nykf.service.FileNewService;
import com.basic.modules.oss.cloud.OSSFactory;
import com.basic.modules.sys.entity.SysFileEntity;
import com.basic.modules.sys.entity.SysUserEntity;
import com.basic.modules.sys.service.SysFileService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.math.BigDecimal;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("fileNewServer")
public class FileNewServerImpl extends ServiceImpl<FileNewDao, FileNewEntity> implements FileNewService {

    @Autowired
    FileNewDao fileNewDao;

    @Autowired
    SysFileService sysFileService;

    @Override
    public List<FileNewEntity> getFileListByGlId(FileNewEntity fileNewEntity) {
        return fileNewDao.getFileListByGlId(fileNewEntity);
    }

    @Override
    public R uploadFile(MultipartFile file, Map map) {
        if (file.isEmpty()) {
            return R.error("文件不能为空");
        }

        // 模块类型
        String mklx = map.get("mklx").toString();

        try {
            // 上传文件
            String originalFilename = file.getOriginalFilename();
            long size = file.getSize();
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix, mklx);

            // sys_file
            SysFileEntity saveFile = new SysFileEntity();
            saveFile.setFileName(originalFilename);
            saveFile.setFileType(suffix);
            saveFile.setFileUrl(url);
            saveFile.setFileSize(new BigDecimal(size));
            boolean save = sysFileService.save(saveFile);
            if (save) {
                // n_ykf_file
                long glId = Long.parseLong(map.get("glId").toString());

                FileNewEntity fileNewEntity = new FileNewEntity();
                fileNewEntity.setGlId(glId);
                fileNewEntity.setMklx(mklx);
                fileNewEntity.setFileId(saveFile.getFileId());

                SysUserEntity sysUserEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
                fileNewEntity.setCreateUserId(sysUserEntity.getUserId());
                boolean save1 = this.save(fileNewEntity);

                if (save1) {
                    return R.ok(fileNewEntity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error("上传失败");
    }

    @Override
    public R postDeleteFile(FileNewEntity fileNewEntity) {
        // 删除sys_file
        Long fileId = fileNewEntity.getSysFileEntity().getFileId();
        sysFileService.removeById(fileId);
        // 删除n_ykf_file
        Long ykfFileId = fileNewEntity.getYkfFileId();
        this.removeById(ykfFileId);
        // 删除oss云存储
        OSSFactory.build().deleteFile(fileNewEntity.getSysFileEntity().getFileUrl());
        return R.ok();
    }

    @Override
    public R postDownLoadFile(FileNewEntity fileNewEntity) {
        String ossUrl = fileNewEntity.getSysFileEntity().getFileUrl();
        String[] parts = ossUrl.replaceFirst("https://", "").split("/", 2);
        // new-yuekefu
        String bucketName = parts[0].split("\\.")[0];
        // new-yuekefu/gjjl/20250513/2a86c2bb8127415ea039201f5bf72569.png
        String objectKey = parts[1];

        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectKey);
        request.setExpiration(new Date(System.currentTimeMillis() + 3600 * 1000));
        // 强制浏览器下载（避免预览）
        request.setMethod(HttpMethod.GET);
        // 手动拼接 response headers 到 URL 参数
        Map<String, String> params = new HashMap<>();
        try {
            // 关键：通过 response-* 参数控制下载行为,如果下载文件名称需要为正常的fileName,在这里加
            /*
             String fileName = fileNewEntity.getSysFileEntity().getFileName();
             String encodedFileName = URLEncoder.encode(fileName, "UTF-8")
            .replaceAll("\\+", "%20"); // 处理空格
             params.put("response-content-disposition",
            "attachment; filename=\"" + encodedFileName + "\"");
             */
            params.put("response-content-disposition",
                    "attachment");
        } catch (Exception e) {
            throw new RuntimeException("文件名编码失败", e);
        }
        request.setQueryParameter(params);
        URL url = OSSFactory.build().getDownLoadUrl(request);
        return R.ok(url.toString());
    }
}